package com.example.demo.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.system.entity.DictItem;
import com.example.demo.system.entity.DictType;
import com.example.demo.system.mapper.DictItemMapper;
import com.example.demo.system.mapper.DictTypeMapper;
import com.example.demo.system.service.DictService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("iDictService")
@RequiredArgsConstructor
public class DictServiceImpl extends ServiceImpl<DictTypeMapper, DictType> implements DictService {

    @Autowired
    private DictItemMapper dictItemMapper;

    // ----------------- 字典类型管理 -----------------
    @Override
    public Page<DictType> getDictTypePage(Page<DictType> page,String typeName) {
        QueryWrapper<DictType> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(typeName)){
            wrapper.like("type_name", typeName);
        }
        return baseMapper.selectPage(page, wrapper);
    }

    @Override
    public void saveDictType(DictType dictType) {
        save(dictType);
    }

    @Override
    public void updateDictType(DictType dictType) {
        updateById(dictType);
    }

    @Override
    public void deleteDictType(Long id) {
        removeById(id);
    }

    // ----------------- 字典项管理 -----------------
    @Override
    @Cacheable(value = "dictCache", key = "#typeCode")
    public List<DictItem> getDictItemsByType(String typeCode) {
        return dictItemMapper.selectByTypeCode(typeCode);
    }

    @Override
    public Map<String, String> getDictMapByType(String typeCode) {
        List<DictItem> items = getDictItemsByType(typeCode);
        return items.stream()
                .collect(Collectors.toMap(DictItem::getItemKey, DictItem::getItemValue));
    }

    @Override
    @CacheEvict(value = "dictCache", allEntries = true)
    public void saveDictItem(DictItem dictItem) {
        dictItemMapper.insert(dictItem);
    }

    @Override
    @CacheEvict(value = "dictCache", allEntries = true)
    public void updateDictItem(DictItem dictItem) {
        dictItemMapper.updateById(dictItem);
    }

    @Override
    @CacheEvict(value = "dictCache", allEntries = true)
    public void deleteDictItem(Long id) {
        dictItemMapper.deleteById(id);
    }

    // ----------------- 缓存管理 -----------------
    @Override
    @CacheEvict(value = "dictCache", allEntries = true)
    public void refreshDictCache() {
        // 清空缓存，下次访问自动加载最新数据
    }
}
